<template>
  <div class="user-page-com">
    <div class="filter-contain">
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        label-width="80px"
        label-position="right"
        class="user-filter-form"
        :inline="true"
      >
        <el-form-item prop="userNumber" label="员工编号" class="form-input">
          <el-input
            clearable
            v-model="queryForm.userNumber"
            placeholder="请输入员工编号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="userName" label="姓名" class="form-input">
          <el-input
            clearable
            v-model="queryForm.userName"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="userAccount" label="账户" class="form-input">
          <el-input
            clearable
            v-model="queryForm.userAccount"
            placeholder="请输入账户"
          ></el-input>
        </el-form-item>
        <el-form-item prop="originId" label="所属组织" class="form-input">
          <el-tree-select
            clearable
            v-model="queryForm.originId"
            :data="originTreeOptions"
            :props="originDefaultProps"
            default-expand-all
            check-strictly
            placeholder="请选择所属组织"
          ></el-tree-select>
        </el-form-item>
        <el-form-item prop="status" label="状态" class="form-input">
          <el-select
            clearable
            v-model="queryForm.status"
            placeholder="请选择状态"
          >
            <el-option label="正常" value="0"></el-option>
            <el-option label="冻结" value="1"></el-option>
            <el-option label="注销" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="tableLoading"
            @click="handleQuery"
          >
            <template #icon>
              <i-ep-search />
            </template>
            查询</el-button
          >
          <el-button
            type="default"
            @click="handleReset"
            :loading="tableLoading"
          >
            <template #icon>
              <i-ep-refreshLeft />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-btn-contain">
      <el-button type="primary" @click="handleAdd">
        <template #icon>
          <i-ep-plus />
        </template>
        新增
      </el-button>
      <el-dropdown @command="handleStatusCommand">
        <el-button type="default">
          <template #icon>
            <i-ep-editPen />
          </template>
          状态变更
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item :disabled="freeStatusFlag" command="1"
              >冻结</el-dropdown-item
            >
            <el-dropdown-item :disabled="cancelStatusFlag" command="2"
              >注销</el-dropdown-item
            >
            <el-dropdown-item
              :disabled="!(cancelStatusFlag || freeStatusFlag)"
              command="0"
              >恢复</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="table-contain">
      <kt-table
        :tableData="tableData"
        :tableColumns="tableColumns"
        :page-number="queryForm.pageNumber"
        :page-size="queryForm.pageSize"
        :total="queryForm.total"
        showPagination
        @selection-change="handleSelectionChange"
        @getList="getList"
      >
        <template #statusStr="{ row }">
          <el-tag
            v-if="row.status === '0'"
            type="success"
            size="default"
            class="table-tag"
            >{{ row.statusStr }}</el-tag
          >
          <el-tag
            v-else-if="row.status === '1'"
            type="warning"
            size="default"
            class="table-tag"
            >{{ row.statusStr }}</el-tag
          >
          <el-tag
            v-else-if="row.status === '2'"
            type="danger"
            size="default"
            class="table-tag"
            >{{ row.statusStr }}</el-tag
          >
        </template>
        <template #action="{ row }">
          <el-button
            type="primary"
            @click="handleEdit(row)"
            class="table-btn"
            link
          >
            <template #icon>
              <i-ep-edit />
            </template>
            编辑
          </el-button>
          <el-button
            type="primary"
            @click="handleView(row)"
            class="table-btn"
            link
          >
            <template #icon>
              <i-ep-view />
            </template>
            查看
          </el-button>
        </template>
      </kt-table>
    </div>
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      :before-close="clearDialog"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogForm"
        label-width="80px"
        label-position="right"
        :disabled="dialogType === 2"
        inline
        :rules="dialogFormRules"
        class="dialog-user-form"
      >
        <el-form-item prop="userNumber" label="员工编号" class="form-input">
          <el-input
            disabled
            v-model="dialogForm.userNumber"
            placeholder="系统自动生成"
          ></el-input>
        </el-form-item>
        <el-form-item prop="userAccount" label="账户" class="form-input">
          <el-input
            disabled
            v-model="dialogForm.userAccount"
            placeholder="系统自动生成"
          ></el-input>
        </el-form-item>
        <el-form-item prop="originId" label="所属组织" class="form-input">
          <el-tree-select
            v-model="dialogForm.originId"
            :data="originTreeOptions"
            :props="originDefaultProps"
            default-expand-all
            check-strictly
            placeholder="请选择所属组织"
          ></el-tree-select>
        </el-form-item>
        <el-form-item prop="userName" label="姓名" class="form-input">
          <el-input
            v-model="dialogForm.userName"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="userBirth" label="出生日期" class="form-input">
          <el-date-picker
            v-model="dialogForm.userBirth"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="userEmail" label="邮箱" class="form-input">
          <el-input
            v-model="dialogForm.userEmail"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item prop="userCertify" label="证件号" class="form-input">
          <el-input
            v-model="dialogForm.userCertify"
            placeholder="请输入证件号"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :loading="submitLoading" @click="closeDialog"
          >取消</el-button
        >
        <el-button :loading="submitLoading" type="primary" @click="handleSubmit"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getUserInfo, addUser, updateUser, updateUserStatus } from "@/api/user"
import { getOrigins } from "@/api/origin"
import { buildTree } from "@/utils/tools"
import { ElMessage } from "element-plus"

const originDefaultProps = {
  children: "children",
  label: "originName"
}
const initialQueryForm = {
  userNumber: "",
  userAccount: "",
  userName: "",
  originId: "",
  status: "",
  pageSize: 20,
  pageNumber: 1,
  total: 0
}
const initDialogForm = {
  userNumber: "",
  userName: "",
  userAccount: "",
  userEmail: "",
  userCertify: "",
  userBirth: "",
  originId: ""
}
const selectedRows = ref<any>([])
const dialogVisible = ref(false)
const dialogTitle = ref("")
const dialogType = ref(0) // 0:新增 1:编辑 2:查看
const dialogFormRef = ref()
const dialogForm = ref({ ...initDialogForm })
const queryForm = ref({ ...initialQueryForm })
const dialogFormRules = {
  userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  userEmail: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  userCertify: [{ required: true, message: "请输入证件号", trigger: "blur" }],
  userBirth: [{ required: true, message: "请选择出生日期", trigger: "change" }]
}
const submitLoading = ref(false)
const tableLoading = ref(false)
const tableData = ref([])
const queryFormRef = ref()
const originTreeOptions = ref<any[]>([]) // 上级组织下拉选项
const tableColumns = [
  {
    prop: "selection",
    type: "selection",
    width: "55px",
    fixed: "left"
  },
  {
    label: "员工编号",
    prop: "userNumber"
  },
  {
    label: "员工姓名",
    prop: "userName"
  },
  {
    label: "账户",
    prop: "userAccount"
  },
  {
    label: "账户状态",
    prop: "statusStr"
  },
  {
    label: "邮箱",
    prop: "userEmail"
  },
  {
    label: "证件号",
    prop: "userCertify"
  },
  {
    label: "所属组织",
    prop: "originName"
  },
  {
    label: "最近修改时间",
    prop: "updatedAt"
  },
  {
    label: "最近修改人",
    prop: "updatedUserStr"
  },
  {
    label: "创建时间",
    prop: "createdAt"
  },
  {
    label: "创建人",
    prop: "createdUserStr"
  },
  {
    label: "操作",
    prop: "action",
    width: "200px",
    fixed: "right",
    slotName: "action"
  }
]
// 所选是否存在冻结状态
const freeStatusFlag = computed(() => {
  let res: boolean = false
  if (selectedRows.value.length) {
    res = selectedRows.value.some((item: any) => {
      return item.status === "1"
    })
  }
  return res
})

// 所选是否存在注销状态
const cancelStatusFlag = computed(() => {
  let res: boolean = false
  if (selectedRows.value.length) {
    res = selectedRows.value.some((item: any) => {
      return item.status === "2"
    })
  }
  return res
})
// 条件查询
const handleQuery = () => {
  queryForm.value.pageNumber = 1
  getList({
    pageNumber: 1
  })
}
// 重置查询条件
const handleReset = () => {
  queryForm.value = { ...initialQueryForm, pageSize: queryForm.value.pageSize }
  const form = queryFormRef.value
  if (form) {
    form.resetFields()
  }
  getList()
}
// 选择条目
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}
// 处理状态变更
const handleStatusCommand = (status: string) => {
  handleStatusChange(status)
}
// 新增用户
const handleAdd = () => {
  dialogVisible.value = true
  dialogTitle.value = "新增用户"
  dialogType.value = 0
  dialogForm.value = { ...initDialogForm }
  const form = dialogFormRef.value
  if (form) {
    form.clearValidate()
  }
}
// 编辑用户
const handleEdit = (row: any) => {
  dialogVisible.value = true
  dialogTitle.value = "编辑用户"
  dialogType.value = 1
  dialogForm.value = { ...row }
  const form = dialogFormRef.value
  if (form) {
    form.clearValidate()
  }
}
// 查看用户
const handleView = (row: any) => {
  dialogVisible.value = true
  dialogTitle.value = "查看用户"
  dialogType.value = 2
  dialogForm.value = { ...row }
  const form = dialogFormRef.value
  if (form) {
    form.clearValidate()
  }
}
// 弹窗确认
const handleSubmit = () => {
  const form = dialogFormRef.value
  if (form) {
    form.validate((valid: boolean) => {
      if (valid) {
        // 提交表单
        submitLoading.value = true
        try {
          if (dialogType.value === 0) {
            addUserFn(dialogForm.value)
          } else if (dialogType.value === 1) {
            updateUserFn(dialogForm.value)
          } else {
            dialogVisible.value = false
          }
        } catch (error) {
          ElMessage.error("提交失败，请稍后重试！")
          console.error(error) // eslint-disable-line
        } finally {
          submitLoading.value = false
        }
      } else {
        ElMessage.error("请填写完整信息")
      }
    })
  }
}
// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  clearDialog()
}
// 关闭弹窗前的操作
const clearDialog = () => {
  const form = dialogFormRef.value
  if (form) {
    form.resetFields()
  }
  dialogForm.value = { ...initDialogForm }
}
// 获取上级组织树形数据
const getOriginsOptions = async () => {
  try {
    const res = await getOrigins({})

    let originList = res.data.rows
    originList = originList.map((item: any) => {
      item.value = item.originId
      return item
    })
    const treeData = [
      {
        originId: 0,
        originCode: "0",
        value: 0,
        originName: "根组织",
        children: buildTree(originList, "originId", "parentId")
      }
    ]
    originTreeOptions.value = treeData
  } catch (error) {
    ElMessage.error("获取上级组织失败，请稍后重试！")
    console.error(error) // eslint-disable-line
  }
}
// 获取用户信息(param可选)
const getList = async (param: any = {}) => {
  const tempParam = param || {}
  queryForm.value = {
    ...queryForm.value,
    ...tempParam
  }
  tableLoading.value = true
  try {
    const res = await getUserInfo(queryForm.value)
    tableData.value = res.data.rows
    queryForm.value.total = res.data.total
  } catch (error) {
    ElMessage.error("获取用户信息失败，请稍后重试！")
    console.error(error) // eslint-disable-line
  } finally {
    tableLoading.value = false
  }
}
// 新增用户信息
const addUserFn = async (data: any) => {
  try {
    const res = await addUser(data)
    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("新增成功")
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error("新增用户失败，请稍后重试！")
    console.error(error) // eslint-disable-line
  }
}
// 编辑用户信息
const updateUserFn = async (data: any) => {
  try {
    const res = await updateUser(data)
    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("编辑成功")
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error("编辑用户失败，请稍后重试！")
    console.error(error) // eslint-disable-line
  }
}
// 批量冻结/注销/恢复用户
const handleStatusChange = async (status: string) => {
  if (selectedRows.value.length === 0) {
    ElMessage.error("请至少选择一条数据")
    return
  }
  try {
    const res = await updateUserStatus({
      ids: selectedRows.value.map((item: any) => item.userId),
      status
    })
    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("操作成功")
    getList()
  } catch (error) {
    ElMessage.error("操作失败，请稍后重试！")
    console.error(error) // eslint-disable-line
  }
}

// 组件挂载后获取用户信息
onMounted(() => {
  getList()
  getOriginsOptions()
})
</script>

<style lang="scss" scoped>
.user-page-com {
  height: 100%;
  @apply flex flex-col;
  .filter-contain {
    @apply h-auto;
  }
  .table-btn-contain {
    @apply h-auto pb-4;
    :deep(.el-button) {
      @apply mr-4;
    }
  }
  .table-contain {
    @apply flex-1;
  }
}
</style>
